package com.xdh.springcloud.security.jwt;

import com.xdh.springcloud.security.jwt.auth.jwt.JwtAuthenticationFailureHandler;
import com.xdh.springcloud.security.jwt.auth.jwt.JwtAuthenticationProvider;
import com.xdh.springcloud.security.jwt.auth.jwt.JwtTokenAuthenticationProcessingFilter;
import com.xdh.springcloud.security.jwt.auth.jwt.SkipPathRequestMatcher;
import com.xdh.springcloud.security.jwt.common.CustomCorsFilter;
import com.xdh.springcloud.security.jwt.common.config.AuthConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationFailureHandler jwtAuthenticationFailureHandler;

    @Autowired
    private JwtAuthenticationProvider jwtAuthenticationProvider;

    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 不需要校验的地址
     */
    private List<String> permitAllEndpointList = new ArrayList<>();

    private void initPermitAllEndpointList() {
        addPermitAllEndpointList(AuthConfig.AUTHENTICATION_URL);
        addPermitAllEndpointList("/**/favicon.ico");
        addPermitAllEndpointList("/actuator/**");
        addPermitAllEndpointList("/error");
    }

    protected void addPermitAllEndpointList(String urlPattern) {
        urlPattern = StringUtils.trimWhitespace(urlPattern);
        if (!permitAllEndpointList.contains(urlPattern)) {
            permitAllEndpointList.add(urlPattern);
        }
    }

    protected void addExtPermitAllEndpointList() {
    }


    @Bean
    public static PasswordEncoder passwordEncoder() {
        return new SCryptPasswordEncoder();
    }

    protected JwtTokenAuthenticationProcessingFilter buildJwtTokenAuthenticationProcessingFilter(List<String> pathsToSkip, String pattern) throws Exception {
        SkipPathRequestMatcher matcher = new SkipPathRequestMatcher(pathsToSkip, pattern);
        JwtTokenAuthenticationProcessingFilter filter = new JwtTokenAuthenticationProcessingFilter(jwtAuthenticationFailureHandler, matcher);
        filter.setAuthenticationManager(this.authenticationManager);
        return filter;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(jwtAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        initPermitAllEndpointList();
        addExtPermitAllEndpointList();
        http
                .csrf().disable()
                .authorizeRequests().antMatchers(this.permitAllEndpointList.toArray(new String[this.permitAllEndpointList.size()]))
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/**").authenticated() // Protected API End-points

                .and()
                .addFilterBefore(new CustomCorsFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(this.permitAllEndpointList, "/**"), UsernamePasswordAuthenticationFilter.class);
    }
}
